package com.swfgui.queue
{
	import com.swfgui.interfaces.IDisposable;
	import com.swfgui.utils.time.STimer;
	
	import flash.events.EventDispatcher;

	public class WaitForValue extends EventDispatcher implements IDisposable
	{
		private var owner:Object;
		private var propertyName:String;
		private var onValueExist:Function;
		private var onValueExistArgs:Array;
		private var valueTimeOut:Number;
		private var timer:STimer;

		public function WaitForValue()
		{
		}

		public function waitForValue(owner:Object, 
			propertyName:String, 
			onValueExist:Function = null, 
			onValueExistArgs:Array = null, 
			timeOut:Number=0):void
		{
			this.owner = owner;
			this.propertyName = propertyName;
			this.onValueExist = onValueExist;
			this.onValueExistArgs = onValueExistArgs;
			
			if (owner[propertyName])
			{
				onTimeOut();
			}
			else
			{
				this.valueTimeOut = timeOut * 1000;

				//timeOut = 0，无限循环
				timer = new STimer(100, Math.ceil(valueTimeOut / 100), onTick, null, onTimeOut);
				timer.start();
			}
		}

		protected function onTick():void
		{
			if (owner[propertyName])
			{
				onTimeOut();
			}
		}

		protected function onTimeOut():void
		{
			if(onValueExist != null)
			{
				onValueExist.apply(null, onValueExistArgs);
			}
			dispatchEvent(new OperationEvent(OperationEvent.COMPLETE));
			dispose();
		}

		public function dispose():void
		{
			if (hasDisposed)
			{
				return;
			}
			_hasDisposed = true;
			owner = null;
			onValueExist = null;
			onValueExistArgs = null;
			if (timer)
			{
				timer.dispose();
			}
		}

		private var _hasDisposed:Boolean;

		public function get hasDisposed():Boolean
		{
			return _hasDisposed;
		}
	}
}
